<template>
    <!-- 弹窗组件 -->
    <div class="dialog-box">
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900" top="30px">
            <el-form :model="formData" :rules="rules" ref="formRef">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="盘点名称" prop="name">
                            <el-input v-model="formData.name" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="盘点仓库" prop="warehouse_name">
                            <el-input readonly @click="showWarehouseDialog = true" v-model="formData.warehouse_name"
                                suffix-icon="MoreFilled" placeholder="请选择" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="盘点日期" prop="check_date">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="formData.check_date" type="date"
                                placeholder="请选择" style="width: 100%;" />
                        </el-form-item>
           ·         </el-col>
                    <el-col :span="12">
                        <el-form-item label="盘点负责人" prop="manager_name">
                            <el-input suffix-icon="MoreFilled" @click="showManagerDialogFun" readonly
                                style="cursor:pointer;" v-model="formData.manager_name"
                                placeholder="请选择库管人员"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.note" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="table-title" style="margin: 20px 0 10px 0; font-weight: bold;">盘点产品</div>
            <el-table :data="productList" border style="width: 100%; flex: 1;" max-height="60vh" >
                <el-table-column prop="warehouse_name" label="产品名称" align="center">
                    <template #default="scope">
                        <div size="small">
                            {{ scope.row?.product?.name || scope.row.product_name }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="specification" label="规格型号" align="center">
                    <template #default="scope">
                        <div size="small">
                            {{ scope.row?.product?.specification || scope.row.specification }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" align="center">
                    <template #default="scope">
                        <div size="small">
                            {{ scope.row?.product?.unit || scope.row.unit }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="book_num" label="账面数量" align="center">
                    <template #default="scope">
                        <div size="small">
                            {{ scope.row?.product?.stock_num || scope.row.stock_num || scope.row.book_num }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="book_num" label="盘点数量" align="center">
                    <template #default="scope">
                        <el-input type="number" v-model="scope.row.real_num" size="small" />
                    </template>
                </el-table-column>
                <el-table-column prop="note" label="备注" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row.note" size="small" />
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
            v-model:current-page="pageData.page"
            v-model:page-size="pageData.page_size"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" color="#626aef" @click="submitForm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <StorageWarehouseDialog v-model:dialogVisible="showWarehouseDialog" :warehouses="warehouseList"
            @confirm="onWarehouseSelect" />
        <!-- 选人人员 -->
        <SelectManagerDialog ref="outboundManagerRef" @selectPurchasingDirector="handleSelectPurchasingDirector" />
    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import api from "@/api";
import StorageWarehouseDialog from '../StorageWarehouseDialog.vue';
import SelectManagerDialog from '../SelectManagerDialog.vue';

// import SelectManagerDialog from '../';
// 接收父组件传入的值
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    dialogType: {
        type: String,
        default: 'add'
    },
    dialogRow: {
        type: Object,
        default: () => ({})
    }
});
// 表格数据
const productList = ref<Array<StockCheckItem | any>>([]); // Properly type the productList


const emit = defineEmits(['update:dialogVisible', 'submit']);

// 表单ref
const formRef = ref<FormInstance>();

// 表单验证规则
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入盘点名称', trigger: 'blur' }],
    warehouse_name: [{ required: true, message: '请选择盘点仓库', trigger: 'change' }],
    check_date: [{ required: true, message: '请选择盘点日期', trigger: 'blur' }],
    manager_name: [{ required: true, message: '请选择盘点负责人', trigger: 'change' }],
});


const dialogTitle = computed(() => props.dialogType === 'add' ? '新增盘点' : '编辑盘点');

interface StockCheckItem {
    product_no: string;
    product_name: string;
    specification: string;
    unit: string;
    book_num: string;
    real_num: string;
    note: string;
}
interface formData {
    id: string;
    name: string;
    warehouse_id: string;
    warehouse_name: string;
    manager_member_id: string;
    manager_name: string;
    check_date: string;
    note: string;
    stock_check_items: StockCheckItem[];
}



interface warehouseList {
    id: string
    name: string
    code: string
    type: string
    manager: string
    phone: string
    address: string
}

const warehouseList = ref<Array<warehouseList>>([]);
// 表单数据
const formData = reactive<formData>({
    id: '',
    name: '',
    warehouse_id: '',
    warehouse_name: '',
    manager_member_id: '',
    manager_name: '',
    check_date: '',
    note: '',
    stock_check_items: []
});

// 监听对话框显示状态
const dialogVisible = computed({
    get: () => props.dialogVisible,
    set: (val) => {
        emit('update:dialogVisible', val);
    }
});

watch(dialogVisible, (val) => {
    console.log(val, 'llll');
    if (val) {
        initFormData();
    }
});

// 初始化表单数据
const initFormData = async () => {
    // 清空表单
    Object.keys(formData).forEach(key => {
        formData[key] = '';
        productList.value = [];
    });
    
    // 清空用户输入缓存和编辑模式数据
    userInputCache.value = {};
    allEditItems.value = [];
    
    // 重置total值
    total.value = 0;

    //获取仓库列表
    const resData = await api.publicFun.getWarehouseList({ type: 2 });
    if (resData.code == 200) {
        warehouseList.value = resData.data;
    }

    if (props.dialogType === 'edit') {
        const res = await api.product.stock_check_detail({ id: props.dialogRow.id });
        if (res.code === 200) {
            console.log(res.data, 'res.data');
            for (let key in formData) {
                formData[key] = res.data[key];
            }
            // 编辑模式下，存储所有详情数据
            allEditItems.value = res.data.stock_check_items || [];
            total.value = allEditItems.value.length;
            
            // 分页处理详情数据
            const startIndex = (pageData.value.page - 1) * pageData.value.page_size;
            const endIndex = startIndex + pageData.value.page_size;
            productList.value = allEditItems.value.slice(startIndex, endIndex);
            
            // 恢复用户输入
            restoreUserInputFromCache();
        }
    }


};
const outboundManagerRef = ref();
const showManagerDialogFun = () => {
    outboundManagerRef.value.openLoading();
}



let showWarehouseDialog = ref(false);


interface item {
    product: {
        no: string;
        name: string;
        specification: string;
        unit: string;
    };
    real_num: string;
    note?: string; // Make note optional
    book_num: string;
    stock_num: string;
}

interface item2 {
    product_no: string;
    product_name: string;
    specification: string;
    unit: string;
    stock_num: string;
    note?: string; // Make note optional
    real_num: string;
    book_num: string;
}
// 提交表单
const submitForm = async () => {
    if (!formRef.value) return;
    try {
        await formRef.value.validate();
        // 保证book_num和real_num字段有2位小数
        function toFixed2(val: any) {
            let num = Number(val);
            if (isNaN(num)) return '0.00';
            return num.toFixed(2);
        }

        if (props.dialogType === 'add') {
            // 获取所有页面的产品数据（包括用户输入）
            const allProductsWithInput = await getAllProductsWithUserInput();
            formData.stock_check_items = allProductsWithInput.map((item: any) => ({
                product_no: item.product?.no || item.product_no,
                product_name: item.product?.name || item.product_name,
                specification: item.product?.specification || item.specification,
                unit: item.product?.unit || item.unit,
                book_num: toFixed2(item.stock_num),
                note: item.note || '',
                real_num: toFixed2(item.real_num),
            }));
        } else {
            // 编辑模式：需要获取所有页面的数据（包括用户的修改）
            console.log('编辑模式 - 开始获取所有页面数据');
            
            // 先保存当前页的用户输入到缓存
            saveUserInputToCache();
            
            // 获取原始的详情数据（所有页面）
            const detailRes = await api.product.stock_check_detail({ id: formData.id });
            if (detailRes.code === 200) {
                const allOriginalItems = detailRes.data.stock_check_items || [];
                console.log('编辑模式 - 原始所有数据:', JSON.parse(JSON.stringify(allOriginalItems)));
                
                // 将用户的修改应用到所有数据上
                formData.stock_check_items = allOriginalItems.map((item: any) => {
                    const key = item.product_no || item.product?.no || item.no || `${item.id}`;
                    const userInput = userInputCache.value[key];
                    console.log(`查找缓存 - key: ${key}, userInput:`, userInput);
                    
                    const mappedItem = {
                        product_no: item.product_no || item.product?.no || '',
                        product_name: item.product_name || item.product?.name || '',
                        specification: item.specification || item.product?.specification || '',
                        unit: item.unit || item.product?.unit || '',
                        book_num: toFixed2(item.book_num || item.stock_num),
                        note: userInput?.note || item.note || '',
                        real_num: toFixed2(userInput?.real_num || item.real_num),
                    };
                    
                    console.log(`编辑模式 - 映射item ${key}:`, mappedItem);
                    return mappedItem;
                });
            } else {
                ElMessage.error('获取盘点详情失败');
                return;
            }
            
            console.log('编辑模式 - 构建的stock_check_items:', JSON.parse(JSON.stringify(formData.stock_check_items)));
        }

        // 添加或编辑主仓库
        if (props.dialogType === 'add') {
            const res = await api.product.stock_check_add(formData);
            if (res.code === 200) {
                ElMessage.success(res.message);
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.message || '盘点失败');
            }
        }


        // 编辑主仓库
        else if (props.dialogType === 'edit') {
            // 调试：检查formData和stock_check_items
            console.log('提交前的formData:', JSON.parse(JSON.stringify(formData)));
            console.log('提交前的stock_check_items:', formData.stock_check_items);
            
            const editParams = {
                id: formData.id,
                name: formData.name,
                warehouse_id: formData.warehouse_id,
                warehouse_name: formData.warehouse_name,
                manager_member_id: formData.manager_member_id,
                manager_name: formData.manager_name,
                check_date: formData.check_date,
                note: formData.note,
                stock_check_items: formData.stock_check_items
            };
            
            console.log('最终编辑参数:', JSON.parse(JSON.stringify(editParams)));
            
            const res = await api.product.stock_check_edit(editParams);
            if (res.code === 200) {
                ElMessage.success(res.message);
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.message || '盘点失败');
            }
        }

    } catch (error) {
        console.error('表单提交错误', error);
        // ElMessage.error('请检查表单填写是否正确');
    }
};
const pageData = ref({
    page: 1,
    page_size: 10,
    keywords: "",
    spu_id: 0,
    warehouse_id: "" ,   
});
const total = ref(0);

// 添加用户输入缓存
const userInputCache = ref({});

// 编辑模式下存储所有详情数据
const allEditItems = ref([]);

// 保存用户输入到缓存
const saveUserInputToCache = () => {
    console.log('保存用户输入到缓存 - 当前productList:', JSON.parse(JSON.stringify(productList.value)));
    
    productList.value.forEach(item => {
        // 更全面的键生成逻辑，适配不同的数据结构
        const key = item.product?.no || item.product_no || item.no || `${item.id}`;
        if (key) {
            userInputCache.value[key] = {
                real_num: item.real_num || '',
                note: item.note || ''
            };
            console.log(`保存缓存 - key: ${key}, real_num: ${item.real_num}, note: ${item.note}`);
        }
    });
    
    console.log('当前用户输入缓存:', JSON.parse(JSON.stringify(userInputCache.value)));
};

// 从缓存恢复用户输入
const restoreUserInputFromCache = () => {
    productList.value.forEach(item => {
        // 使用与保存缓存相同的键生成逻辑
        const key = item.product?.no || item.product_no || item.no || `${item.id}`;
        if (key && userInputCache.value[key]) {
            item.real_num = userInputCache.value[key].real_num || '';
            item.note = userInputCache.value[key].note || '';
            console.log(`恢复缓存 - key: ${key}, real_num: ${item.real_num}, note: ${item.note}`);
        }
    });
};

// 获取所有产品数据（包括用户输入）
const getAllProductsWithUserInput = async () => {
    // 先保存当前页的用户输入
    saveUserInputToCache();
    
    try {
        // 设置一个较大的页面大小来获取所有数据
        const res = await api.product.product_stock_list({
            ...pageData.value,
            page: 1,
            page_size: 1000 // 设置足够大的页面大小
        });
        
        if (res.code == 200) {
            const allProductsData = res.data.data;
            
            // 为每个产品添加用户输入的数据
            return allProductsData.map(item => {
                const key = item.product?.no || item.product_no || `${item.id}`;
                const userInput = userInputCache.value[key];
                
                if (userInput) {
                    item.real_num = userInput.real_num;
                    item.note = userInput.note;
                }
                
                return item;
            });
        }
    } catch (error) {
        console.error('获取所有产品数据失败:', error);
    }
    
    return [];
};
// 
async function loadProductStock() {
    if (!formData.warehouse_id) return;
    
    // 在加载新数据前保存用户输入
    saveUserInputToCache();
    
    const res = await api.product.product_stock_list(pageData.value);
    if (res.code == 200) {
        productList.value = res.data.data;
        // 设置总数据量，用于分页
        total.value = res.data.total || 0;
        
        // 加载数据后恢复用户输入
        restoreUserInputFromCache();
    }
}
async function onWarehouseSelect(warehouse) {
    formData.warehouse_id = warehouse.id;
    formData.warehouse_name = warehouse.name;
    showWarehouseDialog.value = false;

    // 清空用户输入缓存（切换仓库时）
    userInputCache.value = {};

    // 设置pageData中的warehouse_id，确保API调用时传递正确的仓库ID
    pageData.value.warehouse_id = warehouse.id;
    pageData.value.page = 1; // 重置页码
    await loadProductStock();

    //获取产品列表
    // const res = await api.product.product_stock_list( pageData.value );
    // if (res.code == 200) {
    //     productList.value = res.data.data;
    //     total.value = res.data.total || 0;
    //     console.log(productList.value, 'productList');
    // }
}
const handleSizeChange = (size: number) => {
    pageData.value.page_size = size;
    pageData.value.page = 1;
    
    if (props.dialogType === 'edit') {
        loadEditPageData();
    } else {
        loadProductStock();
    }
};

const handleCurrentChange = (page: number) => {
    pageData.value.page = page;
    
    if (props.dialogType === 'edit') {
        loadEditPageData();
    } else {
        loadProductStock();
    }
};

// 编辑模式下的分页数据加载
const loadEditPageData = () => {
    // 先保存当前页的用户输入
    saveUserInputToCache();
    
    // 分页处理详情数据
    const startIndex = (pageData.value.page - 1) * pageData.value.page_size;
    const endIndex = startIndex + pageData.value.page_size;
    productList.value = allEditItems.value.slice(startIndex, endIndex);
    
    // 恢复用户输入
    restoreUserInputFromCache();
};
interface PurchasingDirector {
    id: number;
    name: string;
    mobile: string;
}

// 处理选择采购负责人
const handleSelectPurchasingDirector = (purchasingDirector: PurchasingDirector) => {

    formData.manager_member_id = String(purchasingDirector.id);
    formData.manager_name = purchasingDirector.name;
};


</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
    margin-bottom: 8px;
}

::v-deep .form-section {
    padding-top: 0px !important;
}

::v-deep .el-form-item__label {
    margin-left: 0px !important;
}

::v-deep .el-form-item__label-wrap {
    margin-left: 0px !important;
}

::v-deep .el-form-item {
    display: block;
}


:deep(.el-dialog) {
    --el-dialog-padding-primary: 0px;
}

:deep(.el-dialog__header) {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

:deep(.dialog-footer) {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
    color: #000;
}

:deep(.el-dialog__body) {
    padding: 20px 10px;
    padding-right: 30px;
}

.table-title {
    font-weight: bold;
    font-size: 16px;
    border-left: 3px solid #3a5fff;
    padding-left: 8px;
}
</style>
